<template>
	<xn-form-container
		:title="formData.id ? '编辑' : '增加'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ style: { width: '120px' } }">
			<a-form-item label="删除原因：" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入删除原因" allow-clear style="width: 360px" />
			</a-form-item>
			<a-form-item label="是否启用：" name="useFlag">
				<a-radio-group v-model:value="formData.useFlag" :options="useFlagOptions" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="deleteReasonForm">
	import { required } from '@/utils/formRules'
	import tool from '@/utils/tool'
	import deleteReasonApi from '@/api/biz/crm/deleteReasonApi'
	import { CommonSwitchEnum } from '@/utils/enum'

	// 定义emit事件
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({
		useFlag: CommonSwitchEnum.TRUE
	})
	// 定义机构元素
	const submitLoading = ref(false)

	const useFlagOptions = tool.dictList('COMMON_SWITCH')

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			formData.value = Object.assign({}, record)
		}
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		formData.value = {
			useFlag: CommonSwitchEnum.TRUE
		}
	}
	// 默认要校验的
	const formRules = {
		name: [required('请输入删除原因')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			deleteReasonApi
				.submitForm(formData.value, formData.value.id)
				.then(() => {
					visible.value = false
					formRef.value.resetFields()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
